package val.lemonde;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Vector;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.os.Parcel;
import android.util.Log;
import android.widget.Toast;

public class SharedDatas {

	public static SharedDatas shared;

	private static final String FILENAME = "article_lus";

	private static final String FILENAME_WIDGET = "widget_articles";

	public static final String PREFERENCE = "lemonde_pref";

	private Vector<String> articles_lues;

	private Context activity;

	private ImageCache cache;

	public SharedDatas(Context a) {
		Log.d("lemonde", "create shared");
		this.articles_lues = new Vector<String>();
		SharedDatas.shared = this;
		activity = a;
		cache = new ImageCache(activity);
		this.set_articles_lues();
	}

	public void setContext(Context a) {
		activity = a;
	}

	public Context getContext() {
		return activity;
	}

	public ImageCache getImageCache() {
		return cache;
	}

	private void set_articles_lues() {
		try {
			FileInputStream fos = activity.openFileInput(FILENAME);
			InputStreamReader isr = new InputStreamReader(fos);
			BufferedReader objBufferReader = new BufferedReader(isr);
			String strLine;
			while ((strLine = objBufferReader.readLine()) != null) {
				this.articles_lues.add(strLine);
			}
			;
			fos.close();
			this.test_length_article_lu();
		} catch (java.io.FileNotFoundException e) {
			Toast.makeText(activity, "Création du fichier de sauvegarde",
					Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			new DialogErreur(this.activity, "ACCES aux donnees partagé", e)
					.show();
			Log.e("lemonde", "ACCES aux donnees partagé " + e.getMessage());
		}
	}

	private void test_length_article_lu() {
		try {
			if (this.articles_lues.size() > 2000) {
				Vector<String> temp = new Vector<String>();
				Log.d("lemonde", "diminue la longeur de la sauvegarde");
				FileOutputStream fos = activity.openFileOutput(FILENAME,
						Context.MODE_PRIVATE);
				for (int i = 1000; i < this.articles_lues.size(); i++) {
					String url_article = this.articles_lues.elementAt(i) + "\n";
					temp.add(this.articles_lues.elementAt(i));
					fos.write(url_article.getBytes());
				}
				fos.flush();
				fos.close();
				this.articles_lues = temp;
			}
		} catch (Exception e) {
			new DialogErreur(this.activity, "ACCES aux donnees partagé", e)
					.show();
			Log.e("lemonde", "ACCES aux donnees partagé " + e.getMessage());
		}
	}

	public void add_articles_lues(String url_article) {
		try {
			if (!this.articles_lues.contains(url_article)) {
				this.articles_lues.add(url_article);
				FileOutputStream fos = activity.openFileOutput(FILENAME,
						Context.MODE_APPEND);
				url_article = url_article + "\n";
				fos.write(url_article.getBytes());
				fos.flush();
				fos.close();
			}
		} catch (Exception e) {
			new DialogErreur(this.activity, "ACCES aux donnees partagé", e)
					.show();
			Log.e("lemonde", "ACCES aux donnees partagé " + e.getMessage());
		}
	}

	public boolean contain_articles_lues(String url_article) {
		if (this.articles_lues.contains(url_article)) {
			// Log.d("ASI","ok_url_lu="+url_article);
			return (true);
		} else {
			// Log.d("ASI","no_url_lu="+url_article);
			return (false);
		}
	}

	public void remove_articles_lues(String linkUri) {
		try {
			if (this.articles_lues.contains(linkUri)) {
				this.articles_lues.remove(linkUri);
				FileOutputStream fos = activity.openFileOutput(FILENAME,
						Context.MODE_PRIVATE);
				for (String url : this.articles_lues) {
					url = url + "\n";
					fos.write(url.getBytes());
				}
				fos.flush();
				fos.close();
			}
		} catch (Exception e) {
			new DialogErreur(this.activity, "ACCÈS aux données partagées", e)
					.show();
			Log.e("lemonde", "ACCÈS aux données partagées " + e.getMessage());
		}

	}

	public void save_widget_posi(int posi) {
		SharedPreferences settings = activity.getSharedPreferences(PREFERENCE,
				0);
		Editor editor = settings.edit();
		editor.putInt("posi_widget", posi);
		editor.commit();
	}

	public int get_widget_posi() {
		SharedPreferences settings = activity.getSharedPreferences(PREFERENCE,
				0);
		return settings.getInt("posi_widget", 0);
	}

	public void save_widget_article(ArrayList<Article> arts) {
		try {
			FileOutputStream fos = activity.openFileOutput(FILENAME_WIDGET,
					Context.MODE_PRIVATE);
			Parcel p1 = Parcel.obtain();
			p1.writeList(arts);
			fos.write(p1.marshall());
			// String temp = "";
			// for (int i = 0; i < arts.size(); i++) {
			// temp = arts.get(i).getTitle() + "\n"
			// + arts.get(i).getUri() + "\n"
			// + arts.get(i).getMediaLink() + "\n"
			// + arts.get(i).isWidgetNew() + "\n";
			// fos.write(temp.getBytes());
			// }
			fos.flush();
			fos.close();
		} catch (java.io.FileNotFoundException e) {
			Log.d("lemonde", "sauver donner partager" + e.getMessage());
		} catch (Exception e) {
			Log.e("lemonde", "ACCES aux donnees partagé save " + e.getMessage());
		}
	}

	@SuppressWarnings("finally")
	public ArrayList<Article> get_widget_article() {
		ArrayList<Article> temp = new ArrayList<Article>();
		try {
			FileInputStream fos = activity.openFileInput(FILENAME_WIDGET);
			// InputStreamReader isr = new InputStreamReader(fos);
			// BufferedReader objBufferReader = new BufferedReader(isr);

			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] b = new byte[1024];
			do {
				int numread = fos.read(b);
				if (numread <= 0)
					break;
				bos.write(b, 0, numread);
			} while (true);
			byte[] bytes = bos.toByteArray();
			Log.d("lemonde", "Taille : " + bytes.length);
			Parcel p2 = Parcel.obtain();
			p2.unmarshall(bytes, 0, bytes.length);
			p2.setDataPosition(0);
			@SuppressWarnings("unchecked")
			ArrayList<Article> arts = p2.readArrayList(Article.class
					.getClassLoader());
			if (arts != null) {
				temp = arts;
			}
			// String strLine;
			// int value = 0;
			// Article ar = new Article();
			// while ((strLine = objBufferReader.readLine()) != null) {
			// value++;
			// if (value == 1) {
			// ar.setTitle(strLine);
			// } else if (value == 2) {
			// ar.setUri(strLine);
			// } else if (value == 3) {
			// ar.setMediaLink(strLine);
			// } else {
			// ar.setWidgetNew(strLine.contains("true"));
			// temp.add(ar);
			// ar = new Article();
			// value = 0;
			// }
			// }
			// ;
			// fos.close();
		} catch (java.io.FileNotFoundException e) {
			Log.d("lemonde", "sauver donner partager" + e.getMessage());
		} catch (Exception e) {
			Log.e("lemonde", "ACCES aux donnees partagé load " + e.getMessage());
		} finally {
			return (temp);
		}
	}

	public void save_widget_new(int newArticle) {
		SharedPreferences settings = activity.getSharedPreferences(PREFERENCE,
				0);
		Editor editor = settings.edit();
		editor.putInt("new_article_widget", newArticle);
		editor.commit();
	}

	public int get_widget_new() {
		SharedPreferences settings = activity.getSharedPreferences(PREFERENCE,
				0);
		return settings.getInt("new_article_widget", 0);
	}

	public void save_categorie_order(ArrayList<Categorie> cats) {
		// on sauve la liste des ids séparé par espace dans l'ordre valide
		StringBuilder save = new StringBuilder("");
		for (Categorie cat : cats) {
			if (cat.isVisible())
				save.append(cat.getId() + " ");
		}

		SharedPreferences settings = activity.getSharedPreferences(PREFERENCE,
				0);
		Editor editor = settings.edit();
		editor.putString("categorie_order", save.toString());
		editor.commit();
	}

	public ArrayList<Categorie> get_categorie(boolean restoreDefault) {
		// on charge les categories par default
		int[] catIds = new int[] { R.array.cat01, R.array.cat02, R.array.cat03,
				R.array.cat04, R.array.cat05, R.array.cat06, R.array.cat07,
				R.array.cat08, R.array.cat09, R.array.cat09b, R.array.cat10, R.array.cat11,
				R.array.cat12, R.array.cat13, R.array.cat14, R.array.cat15,
				R.array.cat16, R.array.cat17 };
		Categorie cat;
		HashMap<String, Categorie> cats = new HashMap<String, Categorie>();
		ArrayList<Categorie> catOrder = new ArrayList<Categorie>();
		Resources res = activity.getResources();
		for (int i = 0; i < catIds.length; i++) {
			String[] categorie = res.getStringArray(catIds[i]);
			cat = new Categorie(res.getResourceName(catIds[i]));
			cat.setName(categorie[0]);
			cat.setUrl(categorie[1]);
			cat.setPosition(i);
			cat.setVisible(categorie[2].equals("true"));
			cats.put(cat.getId(), cat);
			catOrder.add(cat);
		}

		// on voie si il y a des modifications à faire sur les categories
		SharedPreferences settings = activity.getSharedPreferences(PREFERENCE,
				0);
		String idsString = settings.getString("categorie_order", "");
		// pas de modifs ou restaurer le défault
		if (idsString.equals("") || restoreDefault) {
			return (catOrder);
		}
		// modifs
		String[] ids = idsString.split(" ");
		for (Categorie catTemp : catOrder) {
			catTemp.setVisible(false);
		}
		for (int j = ids.length - 1; j >= 0; j--) {
			if (cats.containsKey(ids[j])) {
				cat = cats.get(ids[j]);
				// Log.d("lemonde","Cat-order:"+cat.getId());
				cat.setPosition(j);
				cat.setVisible(true);
				catOrder.remove(cat);
				catOrder.add(0, cat);
			}
		}
		return (catOrder);
	}

	public void setZoomArticle(int zoom) {
		SharedPreferences settings = activity.getSharedPreferences(PREFERENCE,
				0);
		Editor editor = settings.edit();
		editor.putInt("zoom_level", zoom);
		editor.commit();
	}

	public int getZoomArticle() {
		SharedPreferences settings = activity.getSharedPreferences(PREFERENCE,
				0);
		return settings.getInt("zoom_level", 100);
	}

	public void setBooleanPreference(String key, boolean pref) {
		SharedPreferences settings = activity.getSharedPreferences(PREFERENCE,
				0);
		Editor editor = settings.edit();
		editor.putBoolean(key, pref);
		editor.commit();
	}

	public boolean getBooleanPreference(String key) {
		SharedPreferences settings = activity.getSharedPreferences(PREFERENCE,
				0);
		return settings.getBoolean(key, true);
	}

	public boolean isZoomEnabled() {
		SharedPreferences settings = activity.getSharedPreferences(PREFERENCE,
				0);
		return settings.getBoolean("zoom_enabled", true);
	}

	public boolean isLoadImageEnabled() {
		SharedPreferences settings = activity.getSharedPreferences(PREFERENCE,
				0);
		return settings.getBoolean("image_enabled", true);
	}

	public boolean isDescriptionEnabled() {
		SharedPreferences settings = activity.getSharedPreferences(PREFERENCE,
				0);
		return settings.getBoolean("description_enabled", true);
	}

	public boolean isDateEnabled() {
		SharedPreferences settings = activity.getSharedPreferences(PREFERENCE,
				0);
		return settings.getBoolean("date_enabled", true);
	}
}
